package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-04
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;


    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 过滤报警
     */
    @Override
    public void alertFilter() {

        //1.查询所有规则,只需要查询个数即可,以及状态等于1
        long count = this.count(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getStatus, 1));
        if (count<=0) {
            return;//0个规则,则直接返回
        }

        //2. 查询所有设备上报数据
        List alertDatas = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);

        if (CollectionUtils.isEmpty(alertDatas)){
            return ;
        }

        //3. 解析设备上报数据
        List<DeviceData> alertDataList = new ArrayList<>();
        alertDatas.forEach(alertData -> {
            List<DeviceData> deviceDataList = JSONUtil.toList(alertData.toString(), DeviceData.class);
            alertDataList.addAll(deviceDataList);
        });
        //4. 数据报警处理器
        //4.1遍历所有设备上报数据
        alertDataList.forEach(alertData -> {
            //方法重写了
            alertFilter(alertData);
        });



        



    }

    private void alertFilter(DeviceData deviceData) {

        //1.准备对应报警规则  从上报数据中的key和id  找，对应的规则
        List<AlertRule> alertRuleList = this.list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1));
        if (CollectionUtils.isEmpty(alertRuleList)) {
            return ;
        }
        //2. 遍历每一条规则
        alertRuleList.forEach(alertRule -> {
            deviceDataAlarmHandle(alertRule,deviceData);
        });


    }

    @Autowired
    private DeviceMapper    deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private IAlertDataService   alertDataService;
    private void deviceDataAlarmHandle(AlertRule alertRule, DeviceData deviceData) {
        //3. 判断是否在生效时间内
        String[] timeList = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(timeList[0]);//开始时间
        LocalTime endTime = LocalTime.parse(timeList[1]);//结束时间
        //3.1 获取上报时间
        LocalTime alarmTime = LocalDateTimeUtil.of(deviceData.getAlarmTime()).toLocalTime();
        if (alarmTime.isBefore(startTime)|| alarmTime.isAfter(endTime)){
            return ;
        }
        //4.检验数据是否达到阈值
        String iotId = deviceData.getIotId();
        //设置报警数量的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+iotId+":"+deviceData.getFunctionId()+":"+alertRule.getId();

        Double value = alertRule.getValue().doubleValue();
        Double dataValue = Double.valueOf( deviceData.getDataValue());
        int compare = NumberUtil.compare(dataValue, value);//比较
        if ((alertRule.getOperator().equals("<") && compare<0) || alertRule.getOperator().equals(">=") && compare>=0){
            //满足条件，说明达到阈值，触发警报,继续向下执行
            log.info("当前上报的数据符合规则异常");
        }else {
            //不满足条件，则不触发警报
            log.info("当前上报的数据不符合规则异常");
                //      删除redis警报数???
            redisTemplate.delete(aggCountKey);
            return;
        }

        //5. 判断沉默周期是否为空

        String silentKey =CacheConstants.ALERT_SILENT_PREFIX+deviceData.getIotId()+":"+deviceData.getFunctionId()+":"+alertRule.getId();
        String silentData = (String) redisTemplate.opsForValue().get(silentKey);
        if (StringUtils.isNotEmpty(silentData)) {
            return ;   //处于沉默期，则直接返回
        }
        //沉默周期为空,就说明不在沉默期，继续执行
        //6. 判断持续周期是否相等
        //6.1 查询报警次数是否相等alertSilentPeriod
        String aggCountData = (String) redisTemplate.opsForValue().get(aggCountKey);//获取报警次数
        Integer count = 0;
        if (StringUtils.isEmpty(aggCountData)){
            //如果会是空，就设置默认值为1
            count=1;
        }else {
            count=Integer.valueOf(aggCountData)+1;
        }

        //6.1然后判断报警次数是否大于目标数
        if (ObjectUtil.notEqual(alertRule.getDuration(),count)) {
            redisTemplate.opsForValue().set(aggCountKey,String.valueOf(count));//设置报警次数,不相等就设置
            return;
        }

        //7.校验全部通过，则进行报警
        //7.1 删除redis中的报警次数
        redisTemplate.delete(aggCountKey);

        //7.2 添加redis中的沉默周期
        redisTemplate.opsForValue().set(silentKey,"1",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //7.3 发送报警数据，需要找到对应的人
        //用集合存储
        List<Long> userIds = new ArrayList<>();

        //首先需要判断类型 0：老人异常数据，1：设备异常数据
        if (alertRule.getAlertDataType().equals(0)){
            //老人异常数据

            if (deviceData.getLocationType().equals(0)){
                //如果是报警手表
                //通过老人id查找到对应的护理员列表
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)){
                //如果是睡眠监测带，绑定的床位信息，就这个
                //通过床位id查到对应的护理员列表
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else {
            //设备异常数据,就通知维修员
            userIds =sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        //无论是设备异常还是老人异常，都需要通知管理员
        List<Long> sysUserIds = sysUserRoleMapper.selectUserIdByRoleName("系统管理员");

        //合并系统和其他用户的id信息
        Collection<Long> allUserIds = CollUtil.addAll(userIds, sysUserIds);
        //去重
        allUserIds = CollUtil.distinct(allUserIds);
        //8、批量保存报警数据
        insertAlertData(allUserIds,alertRule,deviceData);



    }

    /**
     * 插入报警数据
     * @param allUserIds
     * @param alertRule
     * @param deviceData
     */
    private void insertAlertData(Collection<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        // 对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        // 心率<60,持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(Integer.valueOf(alertRule.getAlertDataType()+""));
        // 遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());

        // 批量保存
        alertDataService.saveBatch(list);
    }
}
